package com.yuyou.fn.platform.service.impl;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.platform.service.IAccessTokenService;
import com.yuyou.fn.platform.vo.AccessTokenVo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * AccessToken 表数据服务层接口实现类
 */
@Service
public class AccessTokenServiceImpl implements IAccessTokenService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public String generateToken(Long userId) {
        String token = RandomStringUtils.randomAlphabetic(18);
        token = Base64.encodeBase64URLSafeString(token.getBytes());
        redisTemplate.opsForValue().set(token, String.valueOf(userId), 30, TimeUnit.DAYS);
        return token;
    }

    public AccessTokenVo validAccessToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BusException("token不能为空");
        }

        String userId = (String) redisTemplate.opsForValue().get(token);

        if (userId == null) {
            throw new BusException("accessToken不存在或已过期");
        }

        AccessTokenVo accessTokenVo = new AccessTokenVo();
        accessTokenVo.setUserId(Long.valueOf(userId));
        accessTokenVo.setToken(token);
        return accessTokenVo;
    }


}